import { BadRequestException, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { CreateChatroomDto } from './dto/create-chatroom.dto';
import { UpdateChatroomDto } from './dto/update-chatroom.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { Chatroom } from '@prisma/client';


type chatItemType = {
    id:number
    name:string
    type:boolean
    createTime:Date
    updateTime:Date
    userCount?:number
}

type canJoinType = {
    id:number;
    isJoin?:boolean
    username?:string
    email?:string
    headPic?:string
}

@Injectable()
export class ChatroomService {
    @Inject(PrismaService)
    private prismaService: PrismaService;

    /* 
     - 一对一聊天室
    - 群聊聊天室
        - 加入群聊
        - 退出群聊
    - 聊天室的详细信息
    */

    // 一对一聊天室
    async createOneToOne(friendId:number , userId:number){
        if(!friendId){
            throw new BadRequestException("好友id不能为空")
        }
        // 创建聊天室 
        // 给关系表创建关系
        const { id } = await this.prismaService.chatroom.create({
            data:{
                name:`${friendId}-chatroom${Math.random().toString().slice(2, 4)}`,
                type:false
            }
        })
        await this.prismaService.userChatroom.create({
            data:{
                chatroomId:id,
                userId
            }
        })
        await this.prismaService.userChatroom.create({
            data:{
                chatroomId:id,
                userId:friendId
            }
        })
        return {
            message:"创建成功",
            chatroomId:id
        }
    }

    // 群聊聊天室
    async createGroup(name:string , userId:number){
        const chat = await this.prismaService.chatroom.create({
            data:{
                name,
                type:true
            }
        })
        await this.prismaService.userChatroom.create({
            data:{
                chatroomId:chat.id,
                userId
            }
        })
        return chat
    }

    // 聊天室详细信息
    async info(chatroomId:number){
        // 拿到聊天室id
        // 根据聊天室id 去查 userId
        // 查询user表
        const chat = await this.prismaService.chatroom.findUnique({
            where:{
                id:chatroomId
            }
        })
        const userchatRes = await this.prismaService.userChatroom.findMany({
            where:{
                chatroomId:chat.id
            }
        })
        const userRes = await this.prismaService.user.findMany({
            where:{
                id:{
                    in:userchatRes.map(item => item.userId)
                }
            },
            select:{
                id:true,
                username:true,
                nickName:true,
                email:true,
                createTime:true,
                headPic:true
            }
        })
        return {
            chatroom:chat,
            userlist:userRes
        }
        
    }

    // 可拉取群聊好友列表
    async canJoin(chatroomId:number , userId:number){
        // 获取用户对应的好友列表
        const friends = await this.prismaService.friendship.findMany({
            where: { OR: [{ userId }, { friendId: userId }] }
        })
        const set = new Set<canJoinType>()
        friends.forEach(item => {
            set.add({id:item.friendId})
            set.add({id:item.userId})
        })
        let friendRes = [...set].filter(item => item.id !== userId)
        for (let item of friendRes) {
            let user = await this.prismaService.user.findUnique({
                where: { id: item.id },
                select: {
                    id: true,
                    username: true,
                    email: true,
                    headPic:true
                }
            });
            item.username = user.username
            item.headPic= user.headPic
            item.email = user.email

            // 把已经在群里的成员过滤掉 
            item.isJoin = false
        }

        // 查询 群聊 对应的userId
        let userIds = await this.prismaService.userChatroom.findMany({
            where:{
                chatroomId
            },
            select:{
                userId:true
            }
        })
        let userRes = userIds.map(item => item.userId)
        
        // friendRes.forEach(item => {
        //     userRes.includes(item.id) ? item.isJoin = true : item.isJoin = false
        // })

        // 把已经在群里的成员过滤掉 
        friendRes = friendRes.filter(item => !userRes.includes(item.id))
        return friendRes
    }

    // 加入群聊
    async join(chatroomId:number , userlist:number[]){
        const type = await this.verifyType(chatroomId)
        if(!type){
            throw new BadRequestException("请选择群聊")
        }
        if(!userlist.length){
            throw new BadRequestException("请选择加入的成员")
        }
        let data = userlist.map(item => {
            return {chatroomId , userId:item}
        })
        await this.prismaService.userChatroom.createMany({
            data
        })
        return '加入群聊成功'
    }

    // 校验聊天室是否为群聊
    async verifyType(id:number){
        let {type} = await this.prismaService.chatroom.findUnique({
            where:{id},
            select:{type:true}
        })
        return type
    }
    // 退出群聊
    async quit(chatroomId:number , userId:number){
        const type = await this.verifyType(chatroomId)
        if(!type){
            throw new BadRequestException("一对一不能退出群聊")
        }
        await this.prismaService.userChatroom.deleteMany({
            where:{chatroomId,userId}
        })
        return '退出成功'
    }

    // 聊天室列表
    async list(name:string , userId:number  ){
        // 获取 userChatroom 关系表里的 chatroom id
        const chatroomIdRes = await this.prismaService.userChatroom.findMany({
            where:{
                userId
            },
            select:{
                chatroomId:true
            }
        })
        
        // 根据id 查询 聊天室
        const res :chatItemType[] = await this.prismaService.chatroom.findMany({
            where:{
                id:{
                    in:chatroomIdRes.map(item => item.chatroomId)
                }
            }
        })
        
        for (const item of res) {
            if(item.type){
                item.userCount = await this.prismaService.userChatroom.count({
                    where:{
                        chatroomId:item.id
                    }
                })
            }
        }
        
        return res.filter((item:Chatroom) => item.name.includes(name || '') )
    }

    // 根据用户id（一对一） 查找对应的聊天室id
    async getOneToOne( friendId:number , userId:number ){
        return await this.foundChat(friendId ,userId)
    }

    async foundChat ( friendId:number , userId:number ){
        
        let chatroom1 = await this.prismaService.userChatroom.findMany({
            where:{
                userId
            }
        })
        let chatroom2 = await this.prismaService.userChatroom.findMany({
            where:{
                userId:friendId
            }
        })
        const resChat = chatroom1.filter(item1 => chatroom2.some(item2 => item1.chatroomId === item2.chatroomId));
        let chatInfo = await this.prismaService.chatroom.findMany({
            where:{
                id:{
                    in:resChat.map(item => item.chatroomId)
                }
            }
        })
        
        let filterChat = chatInfo.filter(item => !item.type)
        if(!filterChat.length){
            return false
        }
        
        const res = await this.prismaService.chatroom.findUnique({
            where:{
                id:filterChat[0].id
            },
            select:{
                type:true,
                id:true
            }
        })
        if(res){
            return res.id
        }
    }

}
